# coding:utf-8
from . import api
from ihome.utils.captcha.captcha import captcha
from ihome import redis_store, constants
from flask import current_app, jsonify, make_response, request
from ihome.utils.response_code import RET
from ihome.libs.yuntongxun.sms import CCP
import random


@api.route('/image_codes/<image_code_id>')
def get_image_codes(image_code_id):
    """提供图片验证码"""
    # 名字，验证码真实值，图片的二进制内容
    name, text, image_data = captcha.generate_captcha()
    try:
        # 保存验证码的真实值与编号
        redis_store.setex('image_code_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        # 日志中记录异常
        current_app.logger.error(e)
        response = {
            'errno': RET.DBERR,
            'errmsg_en': 'save image code failed',
            'errmsg_ch': '保存验证码失败'
        }
        return jsonify(response)
    # 返回验证码图片
    response = make_response(image_data)
    response.headers['Content-Type'] = 'image/jpg'
    return response


@api.route("/sms_code/<re(r'1[34578]\d{9}'):mobile>")
def send_sms_code(mobile):
    """发送短信验证码"""
    # 获取参数
    image_code_id = request.args.get('image_code_id')
    image_code = request.args.get('image_code')

    # 校验参数
    if not all([image_code_id, image_code]):
        response = {
            'errno': RET.PARAMERR,
            'errmsg': '参数不完整'
        }
        return jsonify(response)

    # 业务处理
    try:
        real_image_code = redis_store.get('image_code_%s' % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        response = {
            'errno': RET.DBERR,
            'errmsg': '校验图片验证码失败'
        }
        return jsonify(response)
    # 删除redis中的图片验证码，防止用户多次尝试同一个图片验证码
    try:
        redis_store.delete('image_code_%s' % image_code_id)
    except Exception as e:
        current_app.logger.error(e)

    # 创建短信验证码
    sms_code = '%06d' % random.randint(0, 999999)

    # 保存短信验证码
    try:
        redis_store.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        response = {
            'errno': RET.DBERR,
            'errmsg': '保存短信验证码异常'
        }
        return jsonify(response)

    # 发送短信验证码
    try:
        ccp = CCP()
        result = ccp.send_template_sms(mobile, [sms_code, str(constants.SMS_CODE_REDIS_EXPIRES/60)], 1)
    except Exception as e:
        current_app.logger.error(e)
        response = {
            "errno": RET.THIRDERR,
            "errmsg": "发送短信异常"
        }
        return jsonify(response)

    if result == 0:
        # 发送成功
        response = {
            "errno": RET.OK,
            "errmsg": "发送短信成功"
        }
        return jsonify(response)
    else:
        response = {
            "errno": RET.THIRDERR,
            "errmsg": "发送短信失败"
        }
        return jsonify(response)
